/**
 * 系统通用Service
 * 包含 ImageService、
 */
import type { JCRequestOption } from '../ServiceBase';
import { ServiceBase } from '../ServiceBase';
import { ApiPre } from '../../config';

const urlbase = ApiPre;

export class CommonService extends ServiceBase {
  SaveImage(data, option: JCRequestOption = {}) {
    return this.request<string>(`${urlbase}/Image/SaveImage`, { data }, option);
  }

  GetImage(imageId: string) {
    return this.request<string>(`${urlbase}/Image/GetImage`, { imageId });
  }

  /**
   * 获取图片对象
   */
  GetImageOfObject(imageId: string, option: JCRequestOption = {}) {
    return this.request<ImageEm>(`${urlbase}/Image/GetImageOfObject`, { imageId }, option);
  }

  GetImageUrl(imageId: string, isForce = false, usingCache = false) {
    const t = isForce ? new Date().getTime() : new Date().getFullYear() + new Date().getMonth();
    const address = `${window.location.protocol}//${window.location.host}`;
    return `${address}${urlbase}/Image/GetImageFile?imageId=${imageId}&t=${t}${usingCache ? '&usingCache=1' : ''}`;
  }

  GetDefaultImg(_width = '100', _height = '100') {
    const width = Number(_width);
    const height = Number(_height);
    let img = '';
    if (window.document) {
      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas && canvas.getContext && canvas.getContext('2d');
      if (!canvas || !ctx) {
        return '';
      }
      canvas.width = width;
      canvas.height = height;
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = '#F9F9F9';
      ctx.fillRect(0, 0, width, height);
      ctx.fillStyle = '#e1e1e1';
      ctx.font = 'bold 14px sans-serif';
      ctx.fillText(`${width}x${height}`, width / 2, height / 2, width);
      img = canvas.toDataURL('image/png');
    }
    return img;
  }
}

export class ImageEm {
  ImageId = '';
  /**
   * 图片数据base64位,为前端展示格式
   */
  Data = '';
  /**
   * 外部系统URL,本系统不会再进行处理
   */
  ImgUrl = '';
  /**
   * 微信的临时媒体ID,本系统会将文件获取后进行保存,需要依赖微信系统以及登录信息,不可随便用
   */
  WxMediaId = '';
  /**
   * 微信APPID
   */
  WxAppId = '';

  Type = '';

  Module = '';

  Remark = '';
}
